package com.pureman.androidapp;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.text.format.Time;
import android.view.Gravity;
import android.widget.Toast;

import com.pureman.androidapp.utils.LogUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Properties;
import java.util.TreeSet;

/**
 * 全局异常捕获
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    /**
     * 是否开启日志输出
     */

    public static final boolean DEBUG = false;

    /**
     * 系统默认的UncaughtException处理类
     */

    private Thread.UncaughtExceptionHandler mDefaultHandler;

    /**
     * CrashHandler实例
     */
    private static CrashHandler INSTANCE;

    private Context mContext;

    /**
     * 使用Properties来保存设备的信息和错误堆栈信息
     */
    private Properties mDeviceCrashInfo = new Properties();

    private static final String VERSION_NAME = "versionName";
    private static final String VERSION_CODE = "versionCode";
    private static final String STACK_TRACE = "STACK_TRACE";

    /**
     * 错误报告文件的扩展名
     */
    private static final String CRASH_REPOTER_EXTENSION = ".cr";


    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new CrashHandler();
        }
        return INSTANCE;
    }

    /**
     * 初始化，注册Context对象
     * 获取系统默认的UncaughtException处理器
     * 设置该CrashHandler为程序默认处理器
     */

    public void init(Context context) {
        LogUtils.i("CrashHandler-->init");
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }


    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        LogUtils.i("CrashHandler-->uncaughtException");
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        }
    }

    /**
     * 自定义错误处理，收集错误信息
     * 发送错误报告等操作均在此完成
     * 开发者可以根据自己的情况来自定义异常处理逻辑
     */

    private boolean handleException(Throwable ex) {
        LogUtils.i("CrashHandler-->handleException");
        if (ex == null) {
            LogUtils.i("handleException --- ex == null");
            return true;
        }
        final String msg = ex.getLocalizedMessage();
        if (msg == null) {
            return false;
        }
        //使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast toast = Toast.makeText(mContext, "程序出错,即将退出:\r\n" + msg, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                Looper.loop();
            }
        }.start();
        //收集设备信息
        collectCrashDevideInfo(mContext);
        //保存错误报告文件
        saveCrashInfoToFile(ex);
        //发送错误报告到服务器
        return true;
    }


    /**
     * 在程序启动时候，可以调用该函数来发送以前没有发送的报告
     */
    public void sendPreviousReportsToServer() {
        sendCrashReportsToServer(mContext);
    }

    /**
     * 把错误报告发送给服务器，包含新产生的和以前没有发送的
     */
    private void sendCrashReportsToServer(Context context) {
        LogUtils.i("CrashHandler-->sendCrashReportsToServer");
        String[] crFiles = getCrashReportFiles(context);
        if (crFiles != null && crFiles.length > 0) {
            TreeSet<String> sortedFiles = new TreeSet<String>();
            sortedFiles.addAll(Arrays.asList(crFiles));
            for (String fileName : sortedFiles) {
                File cr = new File(mContext.getFilesDir(), fileName);
                postReport(cr);
                //删除已发送的报告
                cr.delete();
            }
        }
    }

    /**
     * 发送错误报告到服务器
     */
    private void postReport(File cr) {

    }

    /**
     * 获取错误报告文件名
     */
    private String[] getCrashReportFiles(Context context) {
        File filesDir = context.getFilesDir();

        File file1 = new File(context.getFilesDir(), "getFilesDir.txt");
        File file2 = new File(context.getCacheDir(), "cache.txt");
        File file3 = new File(context.getExternalCacheDir().getAbsolutePath(), "getExternalCacheDir.txt");
        File file4 = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "getExternalFilesDir.txt");
        File file5 = Environment.getExternalStorageDirectory();
        File file6 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

        LogUtils.i("CrashHandler getCrashReportFiles file0-->" + filesDir.getPath());
        LogUtils.i("CrashHandler getCrashReportFiles file1-->" + file1.getPath());
        LogUtils.i("CrashHandler getCrashReportFiles file2-->" + file2.getPath());
        LogUtils.i("CrashHandler getCrashReportFiles file3-->" + file3.getPath());
        LogUtils.i("CrashHandler getCrashReportFiles file4-->" + file4.getPath());
        LogUtils.i("CrashHandler getCrashReportFiles file5-->" + file5.getPath());
        LogUtils.i("CrashHandler getCrashReportFiles file6-->" + file6.getPath());

        FilenameFilter filter = new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                return filename.endsWith(CRASH_REPOTER_EXTENSION);
            }
        };
        return filesDir.list(filter);
    }

    /**
     * 保存错误信息到文件中
     */
    private String saveCrashInfoToFile(Throwable ex) {
        LogUtils.i("CrashHandler-->saveCrashInfoToFile");
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        String result = info.toString();
        printWriter.close();
        mDeviceCrashInfo.put("EXEPTION", ex.getLocalizedMessage());
        mDeviceCrashInfo.put(STACK_TRACE, result);
        Time t = new Time("GMT+8");
        t.setToNow();  //取得系统时间
        int date = t.year * 10000 + t.month * 100 + t.monthDay;
        int time = t.hour * 10000 + t.minute * 100 + t.second;
        String fileName = "crash-" + date + "-" + time + CRASH_REPOTER_EXTENSION;
        try {
            FileOutputStream trace = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
            mDeviceCrashInfo.store(trace, "");
            trace.flush();
            trace.close();
            return fileName;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            LogUtils.i("an error occured while write report file.." + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 收集程序奔溃的设备信息
     */
    private void collectCrashDevideInfo(Context mContext) {
        LogUtils.i("CrashHandler-->collectCrashDevideInfo");
        PackageManager pm = mContext.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (packageInfo != null) {
                mDeviceCrashInfo.put(VERSION_NAME, "" + packageInfo.versionName == null ? "not set " : packageInfo.versionName);
                mDeviceCrashInfo.put(VERSION_CODE, "" + packageInfo.versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            LogUtils.i("Error while collect package info" + e.getMessage());
            e.printStackTrace();
        }
        //使用反射来收集设备信息，在Build类中包含各种设备信息
        //例如：系统版本号，设备生产商 等帮助挑射程序的有用信息
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                mDeviceCrashInfo.put(field.getName(), "" + field.get(null));
                if (DEBUG) {
                    LogUtils.i(field.getName() + "：" + field.get(null));
                }
            } catch (IllegalAccessException e) {
                LogUtils.i("Error while collect crash info " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
